package com.xzh.homeliving.commodity.service.impl;

import com.xzh.homeliving.commodity.entity.*;
import com.xzh.homeliving.commodity.service.*;
import com.xzh.homeliving.commodity.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xzh.common.utils.PageUtils;
import com.xzh.common.utils.Query;

import com.xzh.homeliving.commodity.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


/**
 * @author xzh
 */
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    // 默认图片路径
    private final String defaultImg = "default.jpg";

    // 默认排序值
    private final Integer defaultSort = 0;
    @Resource
    private SpuInfoDescService spuInfoDescService;

    @Resource
    private SpuImagesService spuImagesService;

    @Resource
    private AtService atService;

    @Resource
    private ProductAttrValueService productAttrValueService;

    @Resource
    private SkuInfoService skuInfoService;

    @Resource
    private SkuImagesService skuImagesService;

    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());

        // 1. 保存 spuInfoEntity
        this.save(spuInfoEntity);
        // 先取出 spuInfoEntity 的id
        Long spuId = spuInfoEntity.getId();
        // 2. 保存spu图片介绍信息
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuId);
        List<String> decript = spuSaveVo.getDecript();
        if(decript == null || decript.isEmpty()) {
            spuInfoDescEntity.setDecript(defaultImg);
        } else {
            // 如果decript有多个，那么将各个数据以逗号形式拼接成为一个长字符串
            spuInfoDescEntity.setDecript(String.join(",", decript));
        }
        spuInfoDescService.saveSpuDescInfo(spuInfoDescEntity);

        // 3. 保存图集信息
        spuImagesService.saveImages(spuId, spuSaveVo.getImages());

        // 4. 保存 spu 对应的基本属性
        List<BaseAttrsVo> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntityList = baseAttrs.stream().map((item) -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuId);
            productAttrValueEntity.setAttrId(item.getAttrId());
            productAttrValueEntity.setQuickShow(item.getShowDesc());
            productAttrValueEntity.setAttrValue(item.getAttrValues());
            AtEntity attrEntity = atService.getById(item.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setAttrSort(defaultSort);
            return productAttrValueEntity;
        }).collect(Collectors.toList());

        productAttrValueService.saveProductAttr(productAttrValueEntityList);

        // 5. 保存 sku 的基本信息
        List<SkusVo> skus = spuSaveVo.getSkus();
        if(skus != null && !skus.isEmpty()) {
            skus.forEach(item -> {
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                skuInfoEntity.setSpuId(spuId);

                // 设置默认图片
                String defaultImage = defaultImg;
                for(ImagesVo image : item.getImages()) {
                    // 当image指定了默认值时，那么就使用指定图片，否则使用默认图片
                    if(image.getDefaultImg() == 1) {
                        defaultImage = image.getImgUrl();
                        break;
                    }
                }
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                // 设置默认销量为 0
                skuInfoEntity.setSaleCount(0L);
                // 设置其分类 id
                skuInfoEntity.setCatalogId(spuSaveVo.getCatalogId());
                // 设置其品牌 id
                skuInfoEntity.setBrandId(spuSaveVo.getBrandId());
                // 设置其价格
                skuInfoEntity.setPrice(item.getPrice());
                // 设置 sku 名
                skuInfoEntity.setSkuName(item.getSkuName());
                // 设置主标题
                skuInfoEntity.setSkuTitle(item.getSkuTitle());
                // 设置副标题
                skuInfoEntity.setSkuSubtitle(item.getSkuSubtitle());
                // 最后将skuInfoEntity保存到数据库中
                skuInfoService.saveSkuInfo(skuInfoEntity);
                // 6. 保存 sku 的图片及信息
                List<SkuImagesEntity> skuImagesEntityList = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setImgSort(0);
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    //System.out.println("sku_id: " + skuImagesEntity.getSkuId());
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuImagesEntity;
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntityList);

                // 7. 添加 sku 的销售属性
                List<AttrVo> attrList = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntityList = attrList.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuSaleAttrValueEntity.setAttrId(attr.getAttrId());
                    skuSaleAttrValueEntity.setAttrSort(0);
                    skuSaleAttrValueEntity.setAttrName(attr.getAttrName());
                    skuSaleAttrValueEntity.setAttrValue(attr.getAttrValue());
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntityList);
            });
        }
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> spuInfoEntityQueryWrapper = new QueryWrapper<>();
        String key = (String)params.get("key");
        String catalogId = (String)params.get("catalogId");
        String brandId = (String)params.get("brandId");
        String status = (String)params.get("status");

        if(StringUtils.isNotBlank(key)) {
            spuInfoEntityQueryWrapper.and((obj) -> obj.eq("id", key).or().like("spu_name", key));
        }
        if(StringUtils.isNotBlank(catalogId) && !"0".equalsIgnoreCase(catalogId)) {
            spuInfoEntityQueryWrapper.eq("catalog_id", catalogId);
        }
        if(StringUtils.isNotBlank(brandId) && !"0".equalsIgnoreCase(brandId)) {
            spuInfoEntityQueryWrapper.eq("brand_id", brandId);
        }
        if(StringUtils.isNotBlank(status)) {
            spuInfoEntityQueryWrapper.eq("publish_status", status);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                spuInfoEntityQueryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        this.baseMapper.updateSpuStatus(spuId, 1);
    }

    @Override
    public void down(Long spuId) {
        this.baseMapper.updateSpuStatus(spuId, 2);
    }
}
